const { app, BrowserWindow, globalShortcut } = require('electron')
const WinState = require('electron-win-state').default
const path = require('path')
const express = require('express')
const { createServer } = require('http')
const { Server } = require('socket.io')
const expressApp = express()
const httpServer = createServer(expressApp);
const io = new Server(httpServer, { cors: true })
var wc
// 创建托盘
const CreateTray = require('./controller/tray.ts')
// 窗口最小化
const WinMini = require('./controller/minMax.ts')
// 打开登录子窗口
const loginWinFn = require('./controller/openLoginWindow.ts')
// 桌面歌词渲染窗口
const desktopLyric = require('./controller/desktopLyric.ts')
// 存储歌词
let lyrics_cb = '';
// 存储关闭桌面渲染进程的布尔值
let desktopLyric_bool = null;

const createWindow = () => {
    // 自定义窗口的状态
    const winState = new WinState({
        defaultWidth: 1030,
        defaultHeight: 670
    })
    // 窗口大小
    const win = new BrowserWindow({
        // 自定义窗口的状态
        ...winState.winOptions,
        minWidth: 1030,
        minHeight: 670,
        // 定义预加载的js脚本
        webPreferences: {
            preload: path.resolve(__dirname, './preload/index.ts')
        },
        show: false,
        frame: false,   // 无边窗口
        icon: path.join(__dirname, './src/assets/logo.png')  // 任务栏自定义图片
    })

    win.loadURL('http://127.0.0.1:5173/')

    // 优雅打开窗口
    win.on('ready-to-show', () => win.show())

    // 打开开发者工具
    wc = win.webContents

    // 窗口状态管理
    winState.manage(win)

    // 创建托盘
    CreateTray(app, win)

    // 窗口最小化/最大化/取消窗口最大化/关闭窗口
    WinMini.mini(win)
    WinMini.max(win)
    WinMini.cancelMax(win)
    WinMini.closeWin(win)

    // 登录窗口
    // loginWinFn(win, port2)
    loginWinFn()
    // 桌面歌词
    desktopLyric()
}

// 在应用准备就绪时调用函数打开 electron 窗口
app.whenReady().then(() => {
    createWindow()
    // 窗口聚焦
    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow();
        }
    });
    // 打开开发者工具
    globalShortcut.register('Ctrl+Shift+O', () => wc.openDevTools())
    // 关闭开发者工具
    globalShortcut.register("Ctrl+Shift+C", () => wc.closeDevTools())
})

//  用户关闭应用
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit();
});

// socket 事件
io.on('connection', (socket) => {
    // 接收歌词
    socket.on('current-lyric', data => lyrics_cb = data)
    // 传递歌词
    socket.on('send-test', (data, callback) => callback(lyrics_cb))
    // 接收关闭桌面歌词的socket事件
    socket.on('closeDesktopLyrics', (data) => desktopLyric_bool = data)
    // 传递关闭桌面歌词容器的socket事件
    socket.on('closeDesktopLyrics_two', (data, callback) => callback(desktopLyric_bool))
})

httpServer.listen(3000)
